package com.jf.blog.util.interceptor;

import com.jf.blog.bean.Userinfo;
import com.jf.blog.service.ApiService;
import com.jf.blog.util.MyConstants;
import com.jf.blog.util.exception.BusinessException;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.Duration;

@Component
public class ApiInterceptor implements HandlerInterceptor {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private ApiService apiService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String api = request.getHeader(MyConstants.API);
        if (StringUtils.isEmpty(api)) {
            throw new BusinessException(403, "href不存在");
        }
        if (!redisTemplate.hasKey(MyConstants.API_KEY + api)) {
            Userinfo vipInfo = apiService.checkPath(api);
            if (vipInfo == null) {
                throw new BusinessException(403, "href不存在");
            }
            redisTemplate.opsForValue().set(MyConstants.API_KEY + api, vipInfo.getUserinfoId().toString(), Duration.ofDays(1));
        }
        return true;
    }
}
